<template>
  <base-layout
    :visibleContent2="true"
    :visibleContent3="true"
    :visibleContent4="true"
    :dialog-title="dialogTitle"
    :dialog-visible="dialogVisible"
    :dialogTitle="dialogTitle"
    :dialogWidth="dialogWidth"
    @dialog-close="dialogClose"
  >
    <template #searchPanel>
      <el-form
        :inline="true"
        ref="fromdata"
        :show-message="false"
        :hide-required-asterisk="true"
        :model="fromdata"
        :rules="rules"
        label-width="90px"
        label-position="right"
      >
        <el-row>
          <el-col :span="12">结算单信息</el-col>
        </el-row>
        <el-divider content-position="center"></el-divider>
        <el-row>
          <el-col :span="6">
            <el-form-item
              label="结算单号:"
              prop="jsCode"
            >
              <el-input
                disabled
                v-model.number="fromdata.jsCode"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="工单号:"
              prop="workOrderCode"
            >
              <el-input
                disabled
                v-model.number="fromdata.workOrderCode"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="工单类型:"
              prop="workOrderCode"
            >
              <el-input v-model.number="fromdata.workOrderCode" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="服务接待:"
              prop="receptionName"
            >
              <el-input
                clearable
                v-model="fromdata.receptionName"
                @focus="employeeFocus()"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="车牌号:"
              prop="licensePlateNumber"
            >
              <el-input
                clearable
                v-model="fromdata.licensePlateNumber"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="车型:"
              prop="carModels"
            >
              <CarModel
                v-model="carModels"
                ref="carModel"
                placeholder="车型组件"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="结算员:"
              prop="jsUserName"
            >
              <el-select
                clearable
                placeholder="请选择结算员"
                v-model="fromdata.jsUserName"
              >
                <el-option
                  v-for="item in users"
                  :key="item.id"
                  :value="item.id"
                  :label="item.userName"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="入厂里程数:"
              prop="inFactoryMileage"
            >
              <el-input
                clearable
                v-model="fromdata.inFactoryMileage"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="入场油量:"
              prop="inFactoryOil"
            >
              <OilNum v-model="fromdata.inFactoryOil" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="接车时间:"
              prop="receiveCarTime"
            >
              <el-date-picker
                v-model="fromdata.receiveCarTime"
                type="date"
                style="width: 195px"
                placeholder="请选择"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="结算时间:"
              prop="jsTime"
            >
              <el-date-picker
                disabled
                v-model="fromdata.jsTime"
                type="date"
                style="width: 195px"
                placeholder="请选择"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </template>
    <template
      #contentPanel
      v-if="fromdata.workOrderCode && fromdata.projectList != undefined"
    >
      <ProjectList
        ref="ProjectList"
        @setTotalAmount="setTotalAmount"
        :list="fromdata.projectList"
      />
    </template>

    <template
      #contentPanel2
      v-if="fromdata.workOrderCode && fromdata.partsList != undefined"
    >
      <PartsList
        ref="PartsList"
        @setTotalAmount="setTotalAmount"
        :list="fromdata.partsList"
      />
    </template>

    <template
      #contentPanel3
      v-if="fromdata.workOrderCode && fromdata.jpList != undefined"
    >
      <BoutiqueList
        ref="BoutiqueList"
        @setTotalAmount="setTotalAmount"
        :list="fromdata.jpList"
      />
    </template>

    <template #contentPanel4>
      <div
        class="text_right"
        v-if="fromdata.workOrderCode"
      >
        <p>项目总金额+配件总金额+精品总金额： <span class="color_red">￥{{fromdata.amount}}</span></p>
        <p>项目优惠金额+配件优惠金额+精品优惠金额： <span class="color_red">￥{{fromdata.discountAmount}}</span></p>
        <p>已交定总金额 <span class="color_red">￥0</span></p>
        <p>应付金额 <span class="color_red">￥{{fromdata.shouldAmount}}</span></p>
        <p>
           <el-button
            v-if="fromdata.shouldAmount === 0"
            type="primary"
            @click="confirmPayOrder"
          >确认支付</el-button>
           <el-button
            type="primary"
            @click="submitCreditOrder"
            
          >挂账出门</el-button>
          <el-button
            type="primary"
            @click="submitOrder"
          >二维码{{settlemenType==1?'退款':'收款'}}</el-button>
        </p>
      </div>
    </template>

    <template #dialog>
      <EmployeeTable
        v-if="dialogTitle=='服务接待列表'"
        @roleIdListSelectCheck="employeListSelectCheck"
      />
      <QRCode
        v-if="dialogTitle=='二维码收款'||dialogTitle=='二维码退款'"
        :amount="fromdata.shouldAmount"
        :paymentType="settlemenType"
        :baseUrl="baseUrl"
        @cancel="dialogVisible=false"
        @paySuccess="paySuccess"
        @refreshCode="submitOrder"
      />
    </template>

  </base-layout>
</template>
<script>
import ProjectList from '@/views/after-sale/workOrderManage/simplicity/components/projectList';//拆分-项目列表
import PartsList from '@/views/after-sale/workOrderManage/simplicity/components/partsList';//拆分-配件列表
import BoutiqueList from '@/views/after-sale/workOrderManage/simplicity/components/boutiqueList';//拆分-精品列表
import CarInfo from '@/views/after-sale/workOrderManage/simplicity/components/carInfo';//拆分-车辆信息
import EmployeeTable from "@/views/after-sale/systemManage/store/components/EmployeeTable";

import { OilNum, CarModel } from "@/components/index"; //导入组件库
import { CarBrand } from '@/components/index' //项目选择组件
import { getStoreId } from '@/utils'
import { userPage } from '@/api/after-sale/personnel/index'
import baseMixin from '@/mixins/base'
import config from "@/views/after-sale/workOrderManage/view/config/index";//导入配置文件
import { getCostCode } from '@/api/after-sale/finance/bill'
import { paymentRefundQrCode, paymentPos, paymentOnAccount, confirmPay } from '@/api/after-sale/payment';
import QRCode from '@/components/QRCode/index';//二维码付款组件

export default {
  components: { CarBrand, ProjectList, PartsList, BoutiqueList, CarInfo, CarModel, OilNum, EmployeeTable, QRCode },
  mixins: [baseMixin({})],
  data () {
    return {
      fromdata: {
        amount: undefined,
        carBrandName: "",
        carModelId: undefined,
        carSeriesId: undefined,
        carBrandId: undefined,
        discountAmount: undefined,
        licensePlateNumber: "",
        partsList: [],
        pickCarId: undefined,
        projectList: [],
        jpList: [],
        receiptsTime: "",
        remark: "",
        shouldAmount: undefined,
        storeId: getStoreId(),
        workOrderCode: "",
        jsCode: '',
        jsTime: new Date(),
        jsUserName: '',
      },
      getConfig: {},
      rules: {},
      dialogVisible: false,
      dialogWidth: '1100px',
      dict: {},
      carModels: [],
      users: [],
      baseUrl: '',
      settlemenType: 2,//默认收款
    }
  },
  watch: {
    "carModels": {
      handler (value) {
        if (value) {
          this.fromdata = {
            ...this.fromdata,
            carBrandId: this.carModels[0],
            carSeriesId: this.carModels[1],
            timeType: this.carModels[2],
            carModelId: this.carModels[3],
          }
        }
      },
      deep: true,
    },
    fromdata: {
      deep: true,
      handler (newValue, oldValue) {
        try {
          let { projectList, jpList, partsList, ...data } = newValue;
          const { ProjectList, PartsList, BoutiqueList } = this.$refs;
          PartsList.partsList = partsList.map(item => {
            item.partsPrice = item.storagePrice;
            return item
          });
          ProjectList.projectList = projectList;
          BoutiqueList.jpList = jpList;
        } catch (error) {
          throw new Error(error);
        }

      }
    }
  },
  async created () {
    this.getjsCode();
    this.getUsers();
    const { id, type, settlemenType } = this.$route.query;
    this.getConfig = config[`workOrderType${type}`];
    let { data, success } = await this.getConfig.getDeatilById(id);
    if (success) {
      data.projectList = data.carProjectLists ? data.carProjectLists : data.projectList;
      this.settlemenType = settlemenType;
      this.fromdata = {
        ...this.fromdata,
        ...data
      };
      this.$refs.carModel.show = false;
      if (this.fromdata.clientCar) {
        const { carBrandId, carSeriesId, timeType, carModelId, licensePlateNumber } = this.fromdata && this.fromdata.clientCar;
        this.fromdata.licensePlateNumber = licensePlateNumber;
        this.carModels = [carBrandId, carSeriesId, timeType, carModelId];
      } else {
        const { carBrandId, carSeriesId, timeType, carModelId } = this.fromdata;
        this.carModels = [carBrandId, carSeriesId, timeType, carModelId];
      }
      setTimeout(() => {
        this.$refs.carModel.show = true;
      }, 100)
    }
  },
  methods: {
    async getjsCode () {
      const { data } = await getCostCode();
      this.fromdata.jsCode = data;
    },
    async getUsers () {
      const { data, success } = await userPage({ storeId: getStoreId() }, 1000, 1);//员工数据,当前门店下
      if (success) {
        this.users = data.content;
      }
    },
    employeeFocus () {
      this.dialogVisible = true;
      this.dialogWidth = "1100px";
      this.dialogTitle = "服务接待列表";
    },
    dialogClose () {
      this.dialogVisible = false;
    },
    //员工选择
    employeListSelectCheck (select) {
      this.fromdata.receptionName = select[0].userName;
      this.fromdata.receptionId = select[0].id;
      this.visible = false;
    },
    //设置总金额、优惠劵查询
    setTotalAmount () {
      const { ProjectList, PartsList, BoutiqueList } = this.$refs;
      this.fromdata.amount = ProjectList.totalAmount + PartsList.totalAmount + BoutiqueList.totalAmount;
      this.fromdata.shouldAmount = ProjectList.totalDiscountAmount + PartsList.totalDiscountAmount + BoutiqueList.totalDiscountAmount;
      this.fromdata.discountAmount = this.fromdata.amount - this.fromdata.shouldAmount;
    },
    paySuccess () {
      this.closeRouter();
    },
    async submitOrder () {
      const { settlemenType } = this.$route.query;
      let { fromdata } = this;
      const { ProjectList, PartsList, BoutiqueList } = this.$refs;
      let params = {
        storeId: fromdata.storeId,
        paymentType: 9,//8 预付收款 9支付收款
        name: fromdata.sendRepairName,
        workOrderNo: fromdata.workOrderCode,
        carNo: fromdata.licensePlateNumber,
        jsCode: fromdata.jsCode,
      };
      try {
        params = {
          ...params,
          jsUserName: fromdata.jsUserName ? this.users.map(item => {
            if (item.id == fromdata.jsUserName) {
              return item;
            }
          })[0].userName : '',
          jsUserId: fromdata.jsUserName,
          projectIds: ProjectList.projectList.map(item => {
            return item.id
          }),
          partsIds: PartsList.partsList.map(item => {
            return item.id
          }),
          jpIds: BoutiqueList.jpList.map(item => {
            return item.id
          }),
        }
      } catch (error) {
        console.error('结算单生成例表信息失败', error)
      } finally {
        const { data, success } = settlemenType == 1 ? await paymentRefundQrCode(params) : await paymentPos(params);
        if (success) {
          this.baseUrl = data;
          this.dialogVisible = true;
          this.dialogWidth = "400px";
          this.dialogTitle = `二维码${settlemenType == 1 ? '退款' : '收款'}`;
        }
      }
    },
    updateOrderType() {
      const { type } = this.$route.query;
      let typeVal = 1;
      if (type == 3) {
        typeVal = 2
      } else if (type == 2) {
        typeVal = 3
      } else if (type == 5) {
        typeVal = 4
      }
      return typeVal
    },
    submitCreditOrder(){
      this.$confirm('是否确认挂账出门', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        const { id } = this.$route.query;
        paymentOnAccount(id, this.updateOrderType(), this.fromdata.workOrderCode).then(response => {
          if (response.success){
            this.$message.success('操作成功');
          }
        })
      })
    },
    confirmPayOrder(){
      const { id } = this.$route.query;
      confirmPay(id, this.updateOrderType(), this.fromdata.workOrderCode).then(response => {
        if (response.success){
          this.$message.success('操作成功');
        }
      })
    }
  },
}
</script>
<style lang="scss" scoped>
.text_right {
  text-align: right;
}
.color_red {
  font-size: 26px;
  color: red;
}
.ft18 {
  font-size: 18px;
}
</style>
